<?php
namespace Budget\BudgetBundle\Helper;
use Budget\BudgetBundle\Entity\Family;
use Budget\BudgetBundle\Helper\DateHelper;

class FamilyHelper
{
    /**
     * Return date with first day of for given month and year
     *
     * @param Family $family
     * @param null $year
     * @param null $month
     * @return string 'Y-m-d 00:00:00'
     */
    public static function getStartMonthDbStr(Family $family, $year = null, $month = null)
    {
        $startDate    = $family->getStartMonthDate($year, $month);
        $startDateStr = $startDate->format(DateHelper::FORMAT_DATE_DB) . " " . DateHelper::DAY_START;
        
        return $startDateStr;
    }
    
    public static function getEndMonthDbStr(Family $family, $year = null, $month = null)
    {
        $endDate      = $family->getEndMonthDate($year, $month);
        $endDateStr   = $endDate->format(DateHelper::FORMAT_DATE_DB) . " " . DateHelper::DAY_END;
        
        return $endDateStr;
    }
    /**
     * 
     * @param \Budget\BudgetBundle\Entity\Family $family
     * @param type $date Expected format mm.yyyy
     */
    public static function getStartMonth(Family $family, $date = null)
    {
        $data = static::getDateData($date);
        return FamilyHelper::getStartMonthDbStr($family, $data['year'], $data['month']);
    }
    
    public static function getEndMonth(Family $family, $date = null)
    {
        $data = static::getDateData($date);
        return FamilyHelper::getEndMonthDbStr($family, $data['year'], $data['month']);
    }
    
    /**
     * Expected format mm.yyyy
     * @param type $date
     * @return type
     */
    protected static function getDateData($date)
    {
        $year  = null;
        $month = null;
        
        if (!is_null($date)) {
            $result = preg_match('/^\d{2}\.\d{4}$/', $date);
            
            if ($result !== 1) {
                throw new \Exception('Given date has wrong format: ' . $date);
            }
            
            $year  = DateHelper::getYear($date);
            $month = DateHelper::getMonth($date);
        }
        
        return array(
            'year'  => $year,
            'month' => $month
        );
    }
    
}

